const { createRepo } = require("../api/repo");
const Contants = require('../contants')
const moment = require('moment')
const { login, getUserRepos } = require("../api/user");
const { NotFoundExecption } = require("../util/exception");

module.exports = class HomeController {
    async repositories(ctx) {
        const { username } = ctx.user
        const res = await getUserRepos(username)
        if (res.code !== 20000) {
            throw new NotFoundExecption(`用户${username}不存在！！！`)
        }
        const userInfo = res.data.userInfo
        const repos = res.data.repos.map(item => {
            const { name, type, description, updated_time } = item
            return {
                name,
                type,
                description,
                updated_time,
                // 新建的仓库没有updated_time
                relative_time: updated_time && moment(updated_time).fromNow(),
                url: `${username}/${name}`,
            }
        })
        ctx.info = userInfo
        ctx.pageTab = 'repo';
        ctx.repos = repos
    }

    async overviews(ctx) {
        const { username } = ctx.user
        const res = await getUserRepos(username)
        if (res.code !== 20000) {
            throw new NotFoundExecption(`用户${username}不存在！！！`)
        }
        const userInfo = res.data.userInfo
        const repos = res.data.repos
        const overviews = res.data.repos.filter(item => item.is_overviews === true).map(item => {
            const { name, type, description, updated_time } = item
            return {
                name,
                type,
                description,
                updated_time,
                url: `${username}/${name}`,
            }
        })
        ctx.info = userInfo
        ctx.pageTab = 'overviews';
        ctx.overviews = overviews
        ctx.repos = repos
    }

    async login(ctx) {
        const username = ctx.username
        const password = ctx.password

        const res = await login(username, password)
        if (res.code === 20000) {
            ctx.token = res.data.token
        }
    }

    async createRepo(ctx) {
        const { username } = ctx.user
        const { comment, name, type } = ctx
        const res = await createRepo(username, name, type, comment)
        if (res.code === 20000) {
            return true
        }
    }
}